package cn.itsource.service.impl;

import cn.itsource.api.LoginFeignClient;
import cn.itsource.constants.RConst;
import cn.itsource.pojo.domain.Customer;
import cn.itsource.mapper.CustomerMapper;
import cn.itsource.pojo.domain.Login;
import cn.itsource.service.ICustomerService;
import cn.itsource.template.WechatTemplate;
import cn.itsource.utils.IdUtil;
import cn.itsource.utils.NameUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 客户 服务实现类
 * </p>
 *
 * @author lifan
 * @since 2024-09-05
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements ICustomerService {

    @Autowired
    private WechatTemplate wechatTemplate;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private LoginFeignClient loginFeignClient;

    @Override
    public void customerRegister(String code) {
        //自动装配获取openId
        String openId = wechatTemplate.getOpenId(code);

        //方法引用 ，好处就是Driver::getOpenId，避免出错openid如果写错就不行，上面一直自己写有可能某个字母大小写问题，下面直接点出来
        LambdaQueryWrapper<Customer> wrapper = new LambdaQueryWrapper<Customer>()
                .eq(Customer::getOpenId, openId)//查询条件
                .select(Customer::getOpenId); //这个是只用openid做查询字段，如果不加，sql语句查询字段会是所有，就是from前面的字段，不加相当于是*号
        //查询
        Customer driver1 = customerMapper.selectOne(wrapper);

        if (driver1 == null) {
            //同步到login表去
            loginFeignClient.create(getLogin(openId));
            // 注册乘客信息
            Customer customer = new Customer();
            customer.setId(IdUtil.getId());
            customer.setPhone("8888888888");
            customer.setOpenId(openId);
            customer.setCreateTime(new Date());
            customer.setName(NameUtil.getName());
            super.save(customer);

        }

    }
    private static Login getLogin(String openId) {
        Login login = new Login();
        //生成uuid
        login.setId(IdUtil.getId());
        //用户名
        login.setUsername(NameUtil.getName());
        // 密码
        login.setPassword("123456");
        //账号类型
        login.setType(RConst.Num.INT_2);
        // 账户启动
        login.setEnabled(true);
        //管理员
        login.setAdmin(RConst.Num.INT_0);
        //昵称
        login.setNickName(NameUtil.getName());
        //微信id
        login.setOpenId(openId);
        //姓名
        login.setNickName(NameUtil.getName());
        //创建时间
        // 获取当前的日期和时间
        login.setCreateTime(new Date());
        return login;
    }
}
